package com.wlcb.jpower.chat.server.handler.customer;


import com.wlcb.jpower.chat.server.handler.MessageHandler;
import com.wlcb.jpower.constant.ChatConfigConstant;
import com.wlcb.jpower.constant.ChatConstant;
import com.wlcb.jpower.im.cache.ImChatRecordCache;
import com.wlcb.jpower.im.cache.SessionCache;
import com.wlcb.jpower.im.model.DataPacket;
import com.wlcb.jpower.module.common.utils.Fc;
import com.wlcb.jpower.utils.WxMpInstance;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;

/**
 * 接收普通消息
 */
@Slf4j
public class CustomerUserHandler extends MessageHandler {

    @Override
    public void handler(ChannelHandlerContext ctx, DataPacket dataPacket) {
        log.info("customer 接收到消息了：{}",dataPacket.toString());
        String result = DataPacket.checkData(dataPacket);
        if (result.length() > 0) {
            DataPacket system = DataPacket.system(dataPacket.getDialogId(), dataPacket.getSendId(),
                    dataPacket.getAppId(), "系统消息：消息格式不正确:<" + result + ">");
            ctx.writeAndFlush(new TextWebSocketFrame(system.toString()));
            return;
        }

        //客服----->用户
        if (ChatConfigConstant.UserType.CUSTOMER.intValue() == dataPacket.getSendType()) {
            ImChatRecordCache imChatRecordCache = ImChatRecordCache.getInstance(dataPacket.getReceiveId());
            if (!Fc.isNull(imChatRecordCache) && imChatRecordCache.getDialogId().equals(dataPacket.getDialogId())) {

                imChatRecordCache.setRecords(dataPacket);
                //先发给自己
                SessionCache.write(dataPacket.getSendId(), dataPacket);
                //在发给用户

                boolean flag = false;
                try {
                    flag = WxMpInstance.getWxMp().switchoverTo(dataPacket.getAppId()).getKefuService().sendKefuMessage(WxMpKefuMessage.TEXT()
                            .toUser(dataPacket.getReceiveId()).content(dataPacket.getContent()).build());
                } catch (WxErrorException e) {
                    e.printStackTrace();
                }
                //发送失败
                if (!flag) {
                    DataPacket system = DataPacket.system(dataPacket.getDialogId(),
                            dataPacket.getSendId(),
                            dataPacket.getAppId(),
                            "系统消息：上一条消息发送失败",
                            ChatConstant.ChatActionEnum.CUSTOMER_USER_MESSAGE.type);
                    SessionCache.write(dataPacket.getSendId(), system);
                    imChatRecordCache.setRecords(system);
                }
            }

        } else {
            SessionCache.write(dataPacket);
        }
    }
}
